export default {
  // 为当前模块开启命名空间
  namespaced: true,
  // 模块的state数据
  state: () => ({
    // 购物车的数据，用来存储购物车中的每个商品的信息对象
    // 每个商品的信息对象包含如下6个属性
    // [goods_id,goods_name,goods_price,goods_count,goods_small_logo,goods_state]
    cart: JSON.parse(uni.getStorageSync('cart') || '[]')
  }),
  mutations: {
    addToCart(state, goods) {
      const findResult = state.cart.find(i => i.goods_id === goods.goods_id)
      if (!findResult) {
        state.cart.push(goods)
      } else {
        findResult.goods_count++
      }
      // 通过commit方法，调用m_cart命名空间下的saveToStorage
      this.commit('m_cart/saveToStorage')
      console.log(state, goods)
    },
    saveToStorage(state) {
      uni.setStorageSync('cart', JSON.stringify(state.cart))
    },
    //更新购物车中商品的勾选状态
    updateGoodsState(state, goods) {
      const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
      console.log(goods)
      if (findResult) {
        findResult.goods_state = !goods.goods_state
        // 通过commit方法，调用m_cart命名空间下的saveToStorage
        this.commit('m_cart/saveToStorage')
      }
    },
    updateGoodsCount(state, goods) {
      const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
      console.log(goods)
      if (findResult) {
        findResult.goods_count = goods.goods_count
        // 通过commit方法，调用m_cart命名空间下的saveToStorage
        this.commit('m_cart/saveToStorage')
      }
    },
    delGoods(state, goods) {
      const findIndex = state.cart.findIndex(x => x.goods_id === goods.goods_id)
      console.log(findIndex)
      if (findIndex !== -1) {
        state.cart.splice(findIndex, 1)
        console.log(state.cart)
        // 通过commit方法，调用m_cart命名空间下的saveToStorage
        this.commit('m_cart/saveToStorage')
      }
    },
    updateCheck(state, check) {
      state.cart.forEach(res => {
        res.goods_state = check
      })
      // 通过commit方法，调用m_cart命名空间下的saveToStorage
      this.commit('m_cart/saveToStorage')
    }
  },
  getters: {
    total(state) {
      const c = state.cart.length
      // let c = 0
      // state.cart.forEach(x => c += x.goods_count)
      return c
    },
    checkedCount(state) {
      return state.cart.filter(x => x.goods_state).reduce((total, item) => {
        return total += item.goods_count
      }, 0)
    },
    sum(state) {
      return state.cart.filter(x => x.goods_state).reduce((total, item) => {
        return total += item.goods_count * item.goods_price
      }, 0).toFixed(2)
    }
  }
}